﻿using System;
using System.Threading;
using System.Windows;
using Oxage.CNC.Models;
using Oxage.Common;

namespace Oxage.CNC
{
	public partial class App : Application
	{
		public App()
		{
			//Logger.Handlers.Add(new ConsoleLogger());
			//Logger.Handlers.Add(new FileLogger());

			//Attach global exception handlers
			AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
			{
				Logger.Log(e.ExceptionObject as Exception);
			};
			this.DispatcherUnhandledException += (sender, e) =>
			{
				Logger.Log(e.Exception);
				e.Handled = true;
			};

			//Initialize main model
			ViewModel = new MainViewModel();
		}

		/// <summary>
		/// Gets or sets a globally accessible MainViewModel instance.
		/// </summary>
		public static MainViewModel ViewModel
		{
			get;
			set;
		}

		/// <summary>
		/// Writes a message to the log window in application.
		/// </summary>
		/// <param name="message"></param>
		public static void WriteLine(string message)
		{
			//Must invoke in GUI thread
			if (ViewModel.View.Dispatcher.Thread != Thread.CurrentThread)
			{
				ViewModel.View.Dispatcher.Invoke(new Action(() =>
				{
					ViewModel.View.Log.WriteLine(message);
				}));
			}
			else
			{
				ViewModel.View.Log.WriteLine(message);
			}
		}
	}
}
